#include<stdio.h>
#include<string.h>
#include<malloc.h>

struct userid
{
	char user[20];
	char passw[30];
	
};

struct userid *data;

int hash(char *us,int m)
{
	int pos,flag=0;
	char a,b;
	a=us[0];
	b=us[1];
	pos=((int)(a)*(int)(b))%m;
	while(flag==0)
	{
		if(strcmp(data[pos].user,"")==0)
		{
			flag=1;
		}
		else
		{
			if(pos==m-1)
			{
				pos=0;
			}
			else
			{
				pos++;
			}
		}
	}
	return pos;
}

int hash_search(char *name,int cou)
{
	int flag=0,pos,i,j=0;
	char a,b;
	a=name[0];
	b-name[1];
	pos=((int)(a)*(int)(b))%cou;
	i=pos;
	while(flag==0)
	{
		if(strcmp(data[pos].user,name)==0)
		{
			return pos;
		}
		else
		{
			if(pos==cou-1)
			{
				pos=0;
				j=1;
			}
			else
			{
				pos++;
			}
		}
		if((j==1) && ((pos-1==i) || (i==(cou-1) && (pos==0))))
		{
			return -1;
		}
	}
}

void getuser(char *a,int n)
{
	int i=0,j=0,pos,k;
	char name[20];
	char h;
	char pass[30];
	while(a[i]!=' ')
	{
		name[i]=a[i];
		i++;
	}
	name[i]='\0';
	i++;
	while(a[i]!='\0')
	{
		pass[j]=a[i];
		i++;
		j++;
	}
	pass[j]='\0';
	pos=hash(name,n);
	strcpy(data[pos].user,name);
	strcpy(data[pos].passw,pass);
}

int main()
{
	FILE *fp1;
	char c,password[30];
	int i=0,recs=0,j=0,sear,try=0;
	char input[20];
	char a[50];
	data=malloc(sizeof(struct userid)*20);
	fp1=fopen("hash.txt","r");
	c=getc(fp1);
	while(c!=EOF)
	{
		if(c=='\n')
		{
			recs++;
		}
		c=getc(fp1);
	}
	if(recs>20)
	{
		data=realloc(data,sizeof(struct userid)*recs);
	}
	while(j<recs)
	{
		strcpy(data[j].user,"");
		strcpy(data[j].passw,"");
		j++;
	}
	fseek(fp1,0,SEEK_SET);
	c=getc(fp1);
	
	while(c!=EOF)
	{
		while(c!='\n')
		{
			a[i]=c;
			i++;
			c=getc(fp1);	
		}
		a[i]='\0';
		getuser(a,recs);
		i=0;
		c=getc(fp1);
	}
	printf("\n		User Authentication\n");
	while(try<3)
	{
		printf("\n//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//**//\n\n");
		printf("	Enter the username(no spaces allowed)(input '1' to exit):");
		scanf("%s",input);
		if(strcmp(input,"1")==0)
		{
			try=4;
		}
		else
		{
			sear=hash_search(input,recs);
			if (sear==-1)
			{
				printf("	Username not found\n\n");
				continue;
			}
			else
			{
				printf("	Enter the password:");
				scanf("%s",password);
				if(strcmp(data[sear].passw,password)!=0)
				{
					try=try+1;
					if(try<3)
					{
						printf("	Wrong password! Please try again\n\n");
					}
					if(try==3)
					{
						printf("\n	More than 3 consecutive wrong tries\n	Access is forbidden!\n	program exiting...\n");
					}
					continue;
				}
				else
				{
					try=0;
					printf("	Correct Password :) User authentication successful\n\n");
				}
			}
		}
	}
	return 0;
}
